package top.scsoul.voes.framework.web.service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * token令牌
 *
 * @author cbt28
 */
@Component
public class TokenService {

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;


    public String createToken(Map<String, Object> Claims) {
        return Jwts.builder()
                .setClaims(Claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expireTime * 1000 * 60))
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    public Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    public String getUsername(String token) {
        return parseToken(token).get("username").toString();
    }

    public String getUsername(HttpServletRequest request) {
        String token = request.getHeader(header);
        return parseToken(token).get("username").toString();
    }


}
